package com.example.memo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.memo.Adapter.NoteAdapter;
import com.example.memo.db.NoteHelper;
import com.example.memo.entity.NoteInfo;
import com.example.memo.entity.UserInfo;

import java.util.List;

public class CreatePage extends AppCompatActivity implements View.OnClickListener {
    private Button commit;
    private EditText et_title,et_content;
    private Toolbar toolbar;
    private NoteHelper noteHelper;
    private NoteInfo noteInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_page);

//        创建
        initView();
//        修改
        initData();
    }

    private void initData() {
        noteInfo = (NoteInfo) getIntent().getSerializableExtra("noteInfo");
        if(noteInfo != null){
            toolbar.setTitle("修改备忘录");
            et_title.setText(noteInfo.getTitle());
            et_content.setText(noteInfo.getContent());
        }
    }

    public void initView(){
        commit = findViewById(R.id.commit);
        et_title = findViewById(R.id.title);
        et_content = findViewById(R.id.content);
        toolbar = findViewById(R.id.toolbar);
        noteHelper = new NoteHelper(this);

        toolbar.setOnClickListener(this);
        commit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if(view == toolbar){
            finish();
        }else if(view == commit){
            String title = et_title.getText().toString();
            String content = et_content.getText().toString();

            if(TextUtils.isEmpty(title) || TextUtils.isEmpty(content)){
                Toast.makeText(CreatePage.this,"标题和内容不能为空！",Toast.LENGTH_SHORT).show();
            }else{
                UserInfo userInfo = UserInfo.getUserInfo();
                if(noteInfo == null){
                    long rowId = noteHelper.createNote(userInfo.getAccount(), title,content);
                    if(rowId < 0){
                        Toast.makeText(CreatePage.this,"创建失败！",Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(CreatePage.this,"创建成功！",Toast.LENGTH_LONG).show();
                        setResult(1);
                    }
                }else {
                    noteHelper.changeNote(noteInfo.getNoteid(),title,content);
                }
                finish();
            }
        }
    }
}